package com.campus.merchant.listener;

import com.campus.merchant.service.OrderService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 订单自动拒单消费者
 */
@Component
@Slf4j
public class OrderAutoRejectConsumer {

    @Resource
    private OrderService orderService;
    
    @Resource
    private ObjectMapper objectMapper;

    /**
     * 监听自动拒单消息
     * @param message 消息内容
     */
    @KafkaListener(topics = "order_auto_reject")
    public void handleAutoRejectOrder(String message) {
        try {
            log.info("接收到自动拒单消息: {}", message);
            
            // 解析JSON消息
            JsonNode jsonNode = objectMapper.readTree(message);
            String orderId = jsonNode.get("orderId").asText();
            Integer operatorType = jsonNode.get("operatorType").asInt();
            
            // 调用订单服务进行拒单处理
            orderService.rejectOrder(orderId, "商家超时未接单，系统自动拒单", operatorType);
            
            log.info("自动拒单处理完成，订单ID: {}, 操作类型: {}", orderId, operatorType);
            
        } catch (Exception e) {
            log.error("处理自动拒单消息失败: {}", message, e);
        }
    }
}